/**
 * Created by Lihn on 15-6-19.
 */
;
(function () {
	//数组去除重复
	var toRepeat = function(arr)
	{
		var n = []; //一个新的临时数组
		for(var i = 0; i < arr.length; i++) //遍历当前数组
		{
			//如果当前数组的第i已经保存进了临时数组，那么跳过，
			//否则把当前项push到临时数组里面
			if (n.indexOf(arr[i]) == -1) n.push(arr[i]);
		}
		return n;
	}
    //定义画布环境变量及场景
    var canvas = null; //创建一个画布
    var stage = null; //创建一个舞台对象
    var scene = null; //定义一个场景对象

    //定义绘制直线的线段
    var beginNode = null;
    var tempNodeA = null;//
    var tempNodeZ = null;
    var tempLink = null;
    var rightMenuOperObj = null;
	//告警处理setIntervalId
	var intervalId;
	//存放告警拓扑节点信息
	//var nodeAlarm={node:拓扑节点,alarmLevel:告警级别,alarmNumber:告警数量}
	var nodeAlarms=[];


    //拖拽之前事件
    var dragTreeBefor = function(treeId,dragNodes){
        if(dragNodes[0].dragFlag == false){
            return false;
        }
        if(dragNodes[0].dragFlag == undefined){
			if(dragNodes[0].type=='bzType'||dragNodes[0].type=='ciType'){
				return false;
			}
        }
        return true;
    }

    //拖拽结束是调用事件
    var dropTreeEnd = function(ev, treeId, treeNodes, targetNode, moveType){
        var id = treeNodes[0].tId;
        id = id+"_span";
        var cls = $("#"+id).attr("class");
        if(treeNodes[0].dragFlag == true){
            addNode(treeNodes[0], ev, true);
            $("#"+id).addClass('current_state');
            treeNodes[0].dragFlag = false;
        }else if(cls == ""){
            addNode(treeNodes[0], ev, true);
            $("#"+id).addClass('current_state');
            treeNodes[0].dragFlag = false;
        }
    }
	var zTreeOnExpand = function(event, treeId, treeNode){
		syncTuoPuAndTreeState();
	}
    //单击展开树
     var zTreeOnClick = function(ev,treeId, treeNode){
		 if(treeNode.isParent){
			var zTree = $.fn.zTree.getZTreeObj("treeDemo");
			//展开节点
			zTree.expandNode(treeNode);
			syncTuoPuAndTreeState();
		 }
     }

    var setting = {
        edit: {
            enable: true,
            showRemoveBtn: false,
            showRenameBtn: false
        },
        data: {
            keep: {
                parent: true,
                leaf: true
            },
            simpleData: {
                enable: true
            }
        },
        view: {
            selectedMulti: false,
            dblClickExpand: false
        },
        callback: {
			onClick: zTreeOnClick,
            beforeDrag: dragTreeBefor,// beforeDrag: 用于捕获节点被拖拽之前的事件回调函数，并且根据返回值确定是否允许开启拖拽操作
            onDrop: dropTreeEnd, //onDrop: 用于捕获节点拖拽操作结束的事件回调函数
			onExpand: zTreeOnExpand
        }

    };

    var operState = {
        state_default: "default",
        state_line: "line",
        state_foldline: "foldline",
        state_fullscreen:"fullscreen",
        state_center:"center",
        state_magnifier:"magnifier",
        state_shrink:"shrink",
        state_recover:"recover",
        state_line:"line",
        state_foldline:"foldline",
        state_eagleye:"eagleye"
    };

    var state = operState.state_default;

    var height, width;//定义容器的高度和宽度

    //开始绘制直线，并初始化线段
    var beginDrawLine = function (action) {
        tempNodeA = new JTopo.Node('tempA');
        tempNodeA.setSize(1, 1);
        tempNodeZ = new JTopo.Node('tempZ');
        tempNodeZ.setSize(1, 1);
        tempLink = createLink(tempNodeA, tempNodeZ, action);//

    }

    var clearDrawLineState = function () {
        tempNodeA = null;
        tempNodeZ = null;
        beginNode = null;
        scene.remove(tempLink);
        tempLink = null;

    }

    var scene_dbclick = function (event) {
        if (event.target instanceof JTopo.Link) {
            scene.remove(event.target);
        }
    }

    /**
	* 创建工具条
	*/
    function createToolBar(target) {
        var $toolbar = $("<div class='detail_r'>"+
							"<div class='tool_bar'>"+
								"<span value='default' class='default' title='默认'></span>"+
								"<span value='line' class='line' title='连线'></span>"+
								"<span value='foldline' class='foldline' title='L形连线'></span>"+
								"<span value='center' class='center' title='居中'></span>"+
						        "<span value='magnifier' class='magnifier' title='放大'></span>"+
						        "<span value='shrink' class='shrink' title='缩小'></span>"+
						        "<span value='recover' class='recover' title='恢复'></span>"+
						        "<span value='eagleye' name=false class='eagleye' title='鹰眼'></span>"+
						        "<select>"+
						        	"<option value='treelayout'>树形布局</option>"+
									"<option value='circlelayout'>圆形布局</option>"+
								"</select>"+
							"</div>"+
							"<input type='button' value='保存' class='save' id='save_tuopu' onclick='saveTopoData()'/>"+
						"</div>");
        if (target) {
            target.append($toolbar);
        }
        //布局切换
        $(target).find("select").change(function (event) {
            var value = $(event.target).attr("value");
            var layout = null;
            switch (value) {
                case "circlelayout":
                	scene.circleLayout();
                    break;
                case "treelayout":
                	scene.treeLayout();
                    break;
            }
        });
        function getFromNodesAndSetLayout(layout) {
        	var fromNodes = [];
			var toIds = [];
			var fromIds = ',';
			//所有的fromId和所有的toId
			scene.childs.forEach(function (element) {
				if (element instanceof JTopo.Link) {
					if(layout.type=='tree'){
						fromNodes.push(element.nodeA);
					}else if(layout.type=='circle'){
						if(fromIds.indexOf(","+element.nodeA.id+",")==-1){
							fromIds+=element.nodeA.id+",";
							fromNodes.push(element.nodeA);
						}
					}
					toIds.push(element.nodeZ.id);
				}else if (element instanceof JTopo.Node) {
					element.layout = layout;
				}
			});
			//过滤出只有from的节点（即跟节点）
			var toIdstr = ","+toIds.join(",")+",";
			for(var i=0;i<fromNodes.length;i++){
				var fNode = fromNodes[i];
				if(toIdstr.indexOf(","+fNode.id+",")>-1){
					fromNodes.splice(i, 1);
					i--;
				}
			}
			return fromNodes;
		}
        /**
         * 圆形布局
         */
        scene.circleLayout = function (){
			var layout = {type: 'circle', radius: 100};
			var fromNodes = getFromNodesAndSetLayout(layout);
			
			var centpoint = scene.getCenterLocation();
			for(var i=0;i<fromNodes.length;i++){
				var step = Math.ceil(i/2);
				if(i==0){
					fromNodes[0].setLocation(centpoint.x, centpoint.y);
				}else if(i%2==0){
					fromNodes[i].setLocation(centpoint.x+step*250, centpoint.y);
				}else{
					fromNodes[i].setLocation(centpoint.x-step*250, centpoint.y);
				}
				JTopo.layout.layoutNode(scene, fromNodes[i], true);
			}
		}
        /**
         * 树形布局
         */
        scene.treeLayout = function () {
        	var layout = {type: 'tree', width: 80, height: 120};
        	var fromNodes = getFromNodesAndSetLayout(layout);
			
        	var centpoint = scene.getCenterLocation();
			for(var i=0;i<fromNodes.length;i++){
				var step = Math.ceil(i/2);
				if(i==0){
					fromNodes[0].setLocation(centpoint.x, 30);
				}else if(i%2==0){
					fromNodes[i].setLocation(centpoint.x+step*40, 30);
				}else{
					fromNodes[i].setLocation(centpoint.x-step*40, 30);
				}
				JTopo.layout.layoutNode(scene, fromNodes[i], true);
			}
		} 
        var css;
        var background_image;
        var background_size;
        var isSelected = false;

        $(".tool_bar span").mouseover(function () {
            background_image = $(this).css("background-image");
            background_size = $(this).css("background-size");
            css = $(this).attr("class");
            $(this).attr("class", "over");
            $(this).css("background-image", background_image);
            $(this).css("background-size", background_size);
        }).mouseout(function () {
            $(this).removeClass('over');
            $(this).addClass(css);
            $(this).css("background-image", background_image);
            $(this).css("background-size", background_size);
        });

        $(".tool_bar span").click(function () {
            $(this).siblings().removeClass('selected');
            $(this).addClass("selected");

            var action = $(this).attr("value");
            state = action;
            switch (action) {
                case operState.state_default:
                    clearDrawLineState();
                    break;
                case operState.state_line:
                    beginDrawLine(action);
                    break;
                case operState.state_foldline:
                    beginDrawLine(action);
                    break;
                case operState.state_default://箭头
                    clearDrawLineState();//
                    break;
                case operState.state_fullscreen: // 全屏
                	runPrefixMethod(stage.canvas, "RequestFullScreen");
                    break;
                case operState.state_center: //居中
                    stage.centerAndZoom(); //缩放并居中显示
                    break;
                case operState.state_magnifier: // 放大
                    stage.zoomOut();
                    break;
                case operState.state_shrink: //缩小
                    stage.zoomIn();
                    break;
                case operState.state_recover: //恢复
                    stage.recover();
                    break;
                case operState.state_eagleye: //鹰眼
                    var flag = $(this).attr("name");
                    if(flag == 'false'){
                        stage.eagleEye.visible = true;
                        $(this).attr("name", 'true');
                    }else{
                        stage.eagleEye.visible = false;
                        $(this).attr("name", 'false');
                    }
                    break;
            }

        });
        return $toolbar;
    }
  //全屏
	var runPrefixMethod = function(element, method) {
        var usablePrefixMethod;
        ["webkit", "moz", "ms", "o", ""].forEach(function(prefix) {
                if (usablePrefixMethod) return;
                if (prefix === "") {
                    // 无前缀，方法首字母小写
                    method = method.slice(0,1).toLowerCase() + method.slice(1);
                }
                var typePrefixMethod = typeof element[prefix + method];
                if (typePrefixMethod + "" !== "undefined") {
                    if (typePrefixMethod === "function") {
                        usablePrefixMethod = element[prefix + method]();
                    } else {
                        usablePrefixMethod = element[prefix + method];
                    }
                }
            }
        );

        return usablePrefixMethod;
    };
    /**
	* 创建资源树
	*/
    function createTreeNode (target, opt) {
        if (!opt || !opt.list) {
            target.append("<h1>无可用数据</h1>");
            return;
        }
        var $treeDiv = $("<div class='nodeList'><div class='listName'>资源列表</div><ul id='treeDemo' class='ztree'></ul></div>");
        target.append($treeDiv);
        $.fn.zTree.init($("#treeDemo"), setting, opt.list);
        //设置点击操作
        $(".detail_title span").addClass("down");
        $(".detail_title span").click(function () {
            if ($(this).parent().siblings().css('display') == 'block') {
                $(this).parent().siblings().hide(300);
                $(this).removeClass("down");
                $(this).addClass("up");
            } else {
                $(this).parent().siblings().show(300);
                $(this).removeClass("up");
                $(this).addClass("down");
            }
        });

        //鼠标经过效果
        $('.get_detail .node').hover(function (e) {
            $(this).css('background', '#d5d5d5')
        }, function () {
            $(this).css('background', '#fff')
        });
        return $treeDiv;
    }

    //添加右键菜单
    function createRihtMenu(target) {
        target.append("<ul class='contextmenu' style='display:none;'><li><a value='delete'>删除</a></li></ul>");
        target.find(".contextmenu li a").click(function (event) {
            //删除节点或连线
            if ($(this).attr("value") == "delete") {
                if (rightMenuOperObj != null) {
                    if (rightMenuOperObj instanceof  JTopo.Link) {
                        scene.remove(rightMenuOperObj);
                    } else if (rightMenuOperObj instanceof  JTopo.Node) {
                        recoverDrag(rightMenuOperObj);
                        //删除节点需删除与该节点所有的连线
                        var outLinks = rightMenuOperObj.outLinks;
                        var inLinks = rightMenuOperObj.inLinks;
                        if (outLinks) {
                            outLinks.forEach(function (link) {
                                scene.remove(link);
                            });
                        }
                        if (inLinks) {
                            inLinks.forEach(function (link) {
                                scene.remove(link);
                            })
                        }
                        scene.remove(rightMenuOperObj);
                    } else if (rightMenuOperObj instanceof  JTopo.Container) {
                        recoverDrag(rightMenuOperObj);
                        //删除节点需删除与该节点所有的连线
                        scene.remove(rightMenuOperObj);
                    }
                }
            }
            $(this).parent().parent().hide();
        });
    }
    //创建拓扑组件
    var createJtopo = function (target, width, height) {
        var $canvas = $("<canvas style='background: ' width='" + width + "px' height='" + height + "px'" +
            " ondrop='dragDrop(event)'></canvas>");
           target.append($canvas);
            $canvas[0].ondrop = function (ev) {
            var dt = ev.dataTransfer;
            var id = dt.getData("id");
            ev.preventDefault();
            ev.stopPropagation()
        }

        $canvas[0].ondragover = function (ev) {
            ev.preventDefault();
            ev.stopPropagation();
            return true;
        }
        return target;
    }
    /**
     *
     * @param node 被拖拽的节点的ｉｄ
     * @param event drop事件
     * @param isClearOriginNode 是否删除被拖拽节点
     */
    var addNode = function (node, event, isClearOriginNode) {
        //获得对象相对于页面的横坐标值；id为对象的id
        var thisX = canvas.offsetLeft;
        //获得对象相对于页面的纵坐标值；
        var thisY = canvas.offsetTop;
        //获得页面滚动的距离；
        //注：document.documentElement.scrollTop为支持非谷歌内核；document.body.scrollTop为谷歌内核
        var thisScrollTop = document.documentElement.scrollTop + document.body.scrollTop;
        event = event || window.event;
        //获得相对于对象定位的横标值 = 鼠标当前相对页面的横坐标值 - 对象横坐标值；
        var x = event.clientX - thisX - scene.translateX;
        //获得相对于对象定位的纵标值 = 鼠标当前相对页面的纵坐标值 - 对象纵坐标值 + 滚动条滚动的高度；
        var y = event.clientY - thisY + thisScrollTop-scene.translateY;

        var icon = node.icon;
        var isSsys = node.isSys;
        //var url = node.url;
        var id = node.id;
		var type = node.type;
        var name = node.name;
        //scene.background = './img/bg.jpg';
        if (isSsys == true&&type=="bzIns") {
            var container = new JTopo.Container(name);
            //container.textPosition = 'Middle_Center';
			container.fillColor ='241,241,241';
			container.alpha = 0.9;
            container.fontColor = '0,0,0';
            container.id = id;
            container.icon = icon;
            //container.url = url;
            container.text = name; // 文字
			container.bundBz=node.bundBz;
            container.font = '10pt 微软雅黑';
			
            container.borderRadius = 30; // 圆角
            container.x = x;
            container.y = y;
            scene.add(container);
			//容器动态包含组件
            addNodesToContainer(scene, container);
        } else if(type="ins") {
            var newNode = new JTopo.Node();
            newNode.id = id;
			newNode.bundBz=node.bundBz;
            newNode.icon = icon;
            newNode.text = name; // 文字
            newNode.font = '10px'; // 字体
            newNode.x = x;
            newNode.y = y;
            newNode.setLocation(x, y)// 位置
            newNode.fontColor = "0,0,0"
            //newNode.setSize(32,32);  // 尺寸
            newNode.borderRadius = 5; // 圆角
            newNode.borderWidth = 2; // 边框的宽度
            newNode.borderColor = '255,255,255'; //边框颜色
            newNode.alpha = 1; //透明度
            newNode.setImage(icon, true);
            //设置部件图片属性
            scene.add(newNode);
            initContainerJTop(scene, newNode);
        }
        if (isClearOriginNode) {
            $(".nodeList .node").remove("#" + node);
        }

    };
	//恢复拖拽功能
    var recoverDrag = function (obj) {
		//节点类型
		var type="";
		if(obj.elementType=="node"){
			type="ins";
		}else if(obj.elementType=="container"){
			type="bzIns";
		}
		//跟据id和type属性获取ztree节点
		var treeNode = getTreeNode(obj.id,type);
		//恢复几点拖拽功能
		treeNode.dragFlag=true;
		$("#"+treeNode.tId+"_span").removeAttr("class");

    }
	//跟据id和type属性获取ztree节点
	var getTreeNode= function(id,type){
		var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
		var nodesId = treeObj.getNodesByParam("id", id, null);
		var nodesType = treeObj.getNodesByParam("type", type, null);
		for(var i=0;i<nodesId.length;i++){
			var nodeType=nodesId[i].type;
			for(var j=0;j<nodesType.length;j++){
				if(nodesId[i].id==nodesType[j].id&&nodeType==nodesType[j].type){
					return nodesType[j];
				}
			}
		}
		return null;
	}
    var initTopo = function (topoData) {
        if (topoData) {
            //加载容器
            if (topoData.containers) {
                topoData.containers.forEach(function (contain) {
                    if (contain) {
                        // 不指定布局的时候，容器的布局为自动(容器边界随元素变化）
                        var container = new JTopo.Container(contain.name); //创建一个容器
						
						container.fillColor ='241,241,241';
						container.alpha = 0.9;
                        container.fontColor = '0,0,0';
                        container.font = '10pt 微软雅黑';
                        
                        container.borderRadius = 20; // 圆角
						
                        container.x = contain.x;
                        container.y = contain.y;
                        container.id = contain.id;
						container.icon= contain.icon;
                        scene.add(container);
                    }
                });
            }

            //加载节点
            if (topoData.nodes) {
                topoData.nodes.forEach(function (n) {
					var node = new JTopo.Node();
					node.id = n.id;
					node.setImage(n.icon, true);
					node.text = n.name; //标题
					node.icon = n.icon;
					node.bundBz=n.bundBz;
					node.x = n.x;
					node.y = n.y;

					node.font = '10px'; // 部件字体
					//设置部件图片属性
					node.fontColor = "0,0,0"
					node.borderRadius = 5; // 圆角
					node.borderWidth = 2; // 边框的宽度
					node.borderColor = '255,255,255'; //边框颜色
					node.alpha = 1; //透明度
					scene.add(node);
					
					//为部件分配组
					initContainerJTop(scene, node);
                    
                });
            }

            if (topoData.links) {
                topoData.links.forEach(function (l) {
                    //循环节点，查找与线对应的节点然后创建连线
                    var nodeA = null;
                    var nodeZ = null;
                    var link = null;

                    scene.childs.forEach(function (element) {
                        if (element instanceof JTopo.Node) {
                            if (l.fromid == element.id) {
                                nodeA = element;
                            } else if (l.toid == element.id) {
                                nodeZ = element;
                            }
                        }
                    })
                    if (nodeA != null && nodeZ != null) {
                        if (l.isFoldLine) {
                            link = new JTopo.FoldLink(nodeA, nodeZ);
                        } else {
                            link = new JTopo.Link(nodeA, nodeZ);
                        }
                        scene.add(link);
                    }
                });
            }
        }
    }
	//同步拓扑图和左侧树的状态
	var syncTuoPuAndTreeState = function(){
		scene.childs.forEach(function (element) {
			var type="";
			if (element instanceof JTopo.Container) {
				type="bzIns"
			} else if (element instanceof  JTopo.Node) {
				type="ins"
			}
			if(type.length>0){
				//跟据id和type属性获取ztree节点
				var treeNode = getTreeNode(element.id,type);
				//去除节点拖拽功能
				treeNode.dragFlag=false;
				$("#"+treeNode.tId+"_span").addClass("current_state");
			}
		});
	}
    var createLink = function (nodeA, nodeB, state) {
        var link = null;
        if (state == operState.state_line) {
            link = new JTopo.Link(nodeA, nodeB);
        } else if (state == operState.state_foldline) {
            link = new JTopo.FoldLink(nodeA, nodeB);
        } else {
			clearDrawLineState();
            console.info("Can't create line! ")
        }
        return link;
    }
	//添加事件
	function sceneBundFunction($target,scene){
		//右键显示菜单
        scene.mousedown(function (e) {
            if (e.button == 2 && ( e.target instanceof JTopo.Link || e.target instanceof JTopo.Node ||e.target instanceof JTopo.Container)) {
                rightMenuOperObj = e.target;
                //右键显示菜单
                $target.find(".contextmenu").css({
                    top: e.pageY-5,
                    left: e.pageX-5
                }).show();
            }
			//清除画线动作
			if(e.target == null || e.target === beginNode || e.target === tempLink){
                if(tempLink!=null){
					scene.remove(tempLink);
				}
				beginNode=null;
            }
        });
		//关闭菜单
		scene.click(function(event){
			if(event.button == 0){// 右键
				// 关闭弹出菜单（div）
				$(".contextmenu").hide();
			}
        });
		//画连接线
		scene.mouseup(function(e){
			if(e.button == 2 && tempLink!=null){
				scene.remove(tempLink);
				beginNode=null;
				return;
			}
			if(e.target != null && e.target instanceof JTopo.Node && tempLink!=null){
				if(beginNode == null){
					beginNode = e.target;
					scene.add(tempLink);
					tempNodeA.setLocation(e.x, e.y);
					tempNodeZ.setLocation(e.x, e.y);
				}else if(beginNode !== e.target){
					var endNode = e.target;
					var l = createLink(beginNode, endNode,state);
					scene.add(l);
					beginNode = null;
					if(tempLink!=null){
						scene.remove(tempLink);
					}
				}else{
					if(tempLink!=null){
						scene.remove(tempLink);
					}
					beginNode = null;
				}
			}else if(tempLink!=null){
				scene.remove(tempLink);
				beginNode = null;
			}
		});
		//划线动作
		scene.mousemove(function(e){
			if(tempNodeZ!=null){
				tempNodeZ.setLocation(e.x, e.y);
			}
        });
		//获取拓扑图数据
		scene.getTopoData=function () {
			var topoData = {containers:[],nodes:[],links:[]};
			scene.childs.forEach(function (element) {
				if (element instanceof JTopo.FoldLink) {
					var link = {};
					link.fromid = element.nodeA.id;
					link.toid = element.nodeZ.id;
					link.isFoldLine = true;
					topoData.links.push(link);
				} else if (element instanceof JTopo.Link) {
					var link = {};
					link.fromid = element.nodeA.id;
					link.toid = element.nodeZ.id;
					link.isFoldLine = false;
					topoData.links.push(link);
				} else if (element instanceof  JTopo.Node) {
					var node = {};
					node.icon = element.icon;
					node.id = element.id;
					node.name = element.text;
					node.bundBz = element.bundBz;
					node.x = element.x;
					node.y = element.y;
					topoData.nodes.push(node);
				} else if (element instanceof  JTopo.Container) {
					var container = {};
					container.icon = element.icon;
					container.id = element.id;
					container.name = element.text;
					container.x = element.x;
					container.y = element.y;
					topoData.containers.push(container);
				}
			});
			return JSON.stringify(topoData);
        }
		//获取拓扑图中的设备id,多个id以逗号隔开
		scene.getInstanceIds=function(){
			var insIds=[];
			scene.childs.forEach(function (element) {
				if (element instanceof  JTopo.Node) {
					insIds.push(element.id);
				}
			});
			return insIds.join(",");
		}
		//显示告警
		scene.showAlarm=function(alarms){
			//var nodeAlarm={node:拓扑节点,alarmLevel:告警级别,alarmNumber:告警数量}
			//清除之前的告警状态
			clearInterval(intervalId);
			for(var i=0;i<nodeAlarms.length;i++){
				nodeAlarms[i].node.alarm=null;
			}
			//获取新的设备告警
			if(alarms!=null&&alarms.length>0){
				for(var i=0;i<alarms.length;i++){
					scene.childs.forEach(function (element) {
						if (element instanceof  JTopo.Node && element.id==alarms[i].instanceId) {
							var nodeAlarm={};
							nodeAlarm.node=element;
							nodeAlarm.alarmLevel=alarms[i].alarmLevel;
							nodeAlarm.alarmNumber=alarms[i].alarmNumber;
							nodeAlarms.push(nodeAlarm);
						}
					});
				}
			}
			//显示告警
			intervalId = setInterval(function(){
				for(var i=0;i<nodeAlarms.length;i++){
					var alarmMsg="";
					var alarmColor="";
					if(nodeAlarms[i].alarmLevel==3){
						alarmMsg="warning告警";
						alarmColor="255,255,0";
					}else if(nodeAlarms[i].alarmLevel==2){
						alarmMsg="error告警";
						alarmColor="255,153,0";
					}else if(nodeAlarms[i].alarmLevel==1){
						alarmMsg="critical告警";
						alarmColor="255,0,0";
					}
					if(nodeAlarms[i].node.alarm == alarmMsg){
						nodeAlarms[i].node.alarm = null;
					}else{
						nodeAlarms[i].node.alarm = alarmMsg;
						nodeAlarms[i].node.alarmColor=alarmColor;
					}
				}
            }, 600);
		}
	}

    //声明插件，调用入口 nodelist:数据源， topoData：初始化数据
    $.fn.topoEdit = function (nodelist, topoData) {
        var $target = $(this);
        var height = $(this).height();
        //创建资源树
        var $treeDiv = createTreeNode($(this), nodelist); //左侧菜单
        var $toolBar = createToolBar($(this)); //工具栏
        var width = $(this).width() - $treeDiv.width();
        $toolBar.width(width - 40);
        createJtopo($toolBar, width-50, height-70); //top图
        createRihtMenu($(this)); //右键菜单
        canvas = $(this).find("canvas")[0];
        stage = new JTopo.Stage(canvas);
        scene = new JTopo.Scene(stage);
        //初始化节点数据
        initTopo(topoData); //加载top图
		sceneBundFunction($target,scene);
		
        return scene;
    }

    //组件加载到容器
    var initContainerJTop = function (se, node) {
		var bundBz = node.bundBz;
		if(bundBz!=null&&bundBz.length>0){
			var arr = toRepeat(bundBz.split(","));
			for(var i = 0; i < arr.length; i++){
				se.childs.forEach(function (c) {
					if (c.elementType == 'container') {
						if (arr[i] == c.id) {
							c.add(node);
							return false;
						}
					}
				});
			}

			//调整布局
			se.childs.forEach(function (a) {
				if (a.elementType == "container") {
					if (a.childs.length == 1) {
						a.layout = JTopo.layout.FlowLayout();
					} else if (a.childs.length > 1) {
						a.layout = JTopo.layout.AutoBoundLayout();
					}
				}
			});
		}
    }

    //容器动态包含组件
    var addNodesToContainer = function (se, con) { //容器
        se.childs.forEach(function (node) {
            if (node == null||node.bundBz==null) return;
            if (node.elementType == "node") {
                if( node.bundBz.length > 1){
                    var arr = toRepeat(node.bundBz.split(","));
                    for(var i = 0; i < arr.length; i++){
                        if (arr[i] == con.id) {
                            con.add(node);
							return false;
                        }
                    }
                }
            }
        });

        //调整布局
        se.childs.forEach(function (a) {
            if (a.elementType == "container") {
                if (a.childs.length == 1) {
                    a.layout = JTopo.layout.FlowLayout();
                    a.setLocation(a.childs[0].x, a.childs[0].y);
                } else if (a.childs.length > 1) {
                    a.layout = JTopo.layout.AutoBoundLayout();
                }
            }
        });
    }

    var ck = function () {
        alert("你点击我了");
    }
})();
var $ondbclk = function(target){
    window.location.href= $(target).attr("url")+"?id="+$(target).attr("id");
}


